﻿using FluentValidation;
using Mes.Domain.BoundedContext;
using Mes.Application.DTO.Inputs.WorkOrders;
using Mes.Application.DTO.Results.WorkOrders;
using Mes.Application.Services.WorkOrders;
using Microsoft.AspNetCore.Mvc;
using Mes.Application.Common;

namespace Mes.Application.Web.Controllers.WorkOrders
{
    /// <summary>
    /// 工单状态控制器
    /// </summary>
    [ApiController]
    [Route("/api/v1")]
    public class JobStateController : ControllerBase
    {
        private readonly IJobStateService _job_StateService;
        private readonly IValidator<UpdateJobStateInput> _updateJobStateInputValidator;
        /// <summary>
        /// 工单状态控制器
        /// </summary>
        /// <param name="job_StateService"></param>
        /// <param name="updateJobStateInputValidator"></param>
        public JobStateController(IJobStateService job_StateService, IValidator<UpdateJobStateInput> updateJobStateInputValidator)
        {
            _job_StateService = job_StateService;
            _updateJobStateInputValidator = updateJobStateInputValidator;
        }

        /// <summary>
        /// 编辑工单状态
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPatch("jobstate")]
        public async Task<ActionResult> UpdateJobStateAsync([FromBody] UpdateJobStateInput input)
        {
            try
            {
                var result = await _updateJobStateInputValidator.ValidateAsync(input);
                if (!result.IsValid)
                {
                    return BadRequest(result.Errors.First().ErrorMessage);
                }
                await _job_StateService.UpdateJobStateAsync(input);
                return Ok();
            }
            catch (CustomException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 查询所有工单状态列表
        /// </summary>
        /// <returns>ItemsResult<JobStatesResult></returns>
        [HttpGet("jobstates")]
        public async Task<ActionResult<ItemsResult<JobStatesResult>>> GetProcessesAsync()
        {
            try
            {
                var response = await _job_StateService.GetAllJobStateAsync();
                return Ok(response);
            }
            catch (CustomException ex)
            {
                return BadRequest(ex.Message);
            }
        }
    }
}
